package cn.edu.lit.jsjxy.CourseExample.chapter4;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.util.AttributeSet;
import android.view.View;

import cn.edu.lit.jsjxy.CourseExample.R;

public class HandWrite extends View
{

    final int POINT = 1;
    final int LINE = 2;
    int startX = 0;
    int startY = 0;
    int endY = 0;
    int endX = 0;
    Bitmap bitmap, newBitmap;
    Paint paint;
    boolean isClear = false;
    int action = 0;


    public HandWrite(Context context, AttributeSet attrs)
    {
        super(context, attrs);
        bitmap = BitmapFactory.decodeResource(getResources(),
                R.drawable.cy);
        //bitmap = Bitmap.createBitmap(400, 300, Bitmap.Config.ARGB_8888);
        newBitmap = Bitmap.createBitmap(bitmap, 0, 0, 400, 300);
        //bitmap = originalImage.copy(originalImage.getConfig(), true);

        paint = new Paint();

        paint.setAntiAlias(true);
        paint.setColor(Color.RED);
        paint.setStyle(Paint.Style.STROKE);
        paint.setStrokeWidth(5);
    }

    @Override
    protected void onDraw(Canvas canvas)
    {
        super.onDraw(canvas);

        if (isClear) {
            canvas.drawColor(getResources().getColor(R.color.darkviolet, null));
            isClear = false;
            return;
        }

        canvas.drawBitmap(newBitmap, 10, 10, null);

        if (action == POINT) {
            canvas.drawPoint(startX, startY, paint);
            return;
        }

        if (action == LINE) {
            canvas.drawLine(startX, startY, endX, endY, paint);
            return;
        }

        //newBitmap = bitmap;
    }

    public void clear()
    {
        isClear = true;
        invalidate();
    }

    public void restore()
    {
        isClear = false;
        invalidate();
    }

    public void drawPoint(int x, int y)
    {
        action = POINT;
        this.startX = x;
        this.startY = y;
        invalidate();
    }

    public void drawLine(int x, int y, int endx, int endy)
    {
        action = LINE;
        this.startX = x;
        this.startY = y;
        this.endX = endx;
        this.endY = endy;
        invalidate();
    }
}